import 'dart:async';

import 'package:event_bus/event_bus.dart';
import 'package:flutter/material.dart';

class EventBusPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _EventBusPageState();
  }
}

class _EventBusPageState extends State<EventBusPage> {
  TextEditingController _filterController = TextEditingController();
  EventBus eventBus = EventBus();
  String text = 'default';
  StreamSubscription streamSubscription;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('event_bus'),
      ),
      body: _body(),
    );
  }

  Widget _body() {
    streamSubscription = eventBus.on().listen((event) {
      setState(() {
        this.text = event;
      });
    });
    return Column(
      children: <Widget>[
        Container(
          margin: EdgeInsets.all(10),
          color: Colors.grey[200],
          child: TextField(
            textAlign: TextAlign.start,
            style: TextStyle(
              fontSize: 16,
              color: Colors.redAccent,
            ),
            decoration: InputDecoration(
              hintText: "请输入过滤",
              border: InputBorder.none,
              prefixIcon: IconButton(
                icon: Icon(
                  Icons.search,
                  color: Colors.grey,
                ),
                onPressed: () {},
              ),
            ),
            controller: _filterController,
            onChanged: (value) {
              eventBus.fire(_filterController.text);
            },
          ),
        ),
        Container(
          padding: EdgeInsets.all(10),
          child: Text(
            text,
            textAlign: TextAlign.center,
          ),
        ),
      ],
    );
  }

  @override
  void dispose() {
    super.dispose();
    streamSubscription.cancel();
  }
}
